package com.mcppro.aidatabase.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 请求日志拦截器
 * 记录所有HTTP请求的基本信息
 * 
 * @author MCP Pro
 */
@Component
@Slf4j
public class RequestLoggingInterceptor implements HandlerInterceptor {

    private static final String REQUEST_ID_HEADER = "X-Request-ID";
    private static final String REQUEST_START_TIME = "REQUEST_START_TIME";
    private static final String REQUEST_ID = "REQUEST_ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        long startTime = System.currentTimeMillis();
        String requestId = getRequestId(request);
        
        // 设置请求属性
        request.setAttribute(REQUEST_START_TIME, startTime);
        request.setAttribute(REQUEST_ID, requestId);
        
        // 设置响应头
        response.setHeader(REQUEST_ID_HEADER, requestId);
        
        // 记录请求开始日志
        log.info("请求开始 - ID: {}, 方法: {}, 路径: {}, 客户端IP: {}, User-Agent: {}", 
                requestId,
                request.getMethod(),
                request.getRequestURI(),
                getClientIpAddress(request),
                request.getHeader("User-Agent"));
        
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                               Object handler, Exception ex) {
        Long startTime = (Long) request.getAttribute(REQUEST_START_TIME);
        String requestId = (String) request.getAttribute(REQUEST_ID);
        
        if (startTime != null) {
            long duration = System.currentTimeMillis() - startTime;
            
            if (ex != null) {
                log.error("请求完成 - ID: {}, 状态: {}, 耗时: {}ms, 异常: {}", 
                        requestId, response.getStatus(), duration, ex.getMessage());
            } else {
                log.info("请求完成 - ID: {}, 状态: {}, 耗时: {}ms", 
                        requestId, response.getStatus(), duration);
            }
        }
    }

    /**
     * 获取或生成请求ID
     */
    private String getRequestId(HttpServletRequest request) {
        String requestId = request.getHeader(REQUEST_ID_HEADER);
        if (requestId == null || requestId.trim().isEmpty()) {
            requestId = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        }
        return requestId;
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}